package com.example.consumer;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.config.Config;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * ClassName: CustomConsumerPartition
 * Package: com.example.consumer
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-08-02
 * Time: 19:19
 */

//消费指定分区的数据
public class CustomConsumerPartition {

    public static void main(String[] args) {

        //创建配置信息
        Properties properties = new Properties();

        //必须要有的参数 连接集群
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"hadoop102:9092");
        //反序列化
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class.getName());

        //配置消费者组信息 一个消费者也要配置
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"test");

        //1.创建消费者
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);

        //指定消费主题对应的分区 调用的方法不同
        ArrayList<TopicPartition> topicPartitions = new ArrayList<>();
        //添加一个topic 封装好了TopicPartition
        topicPartitions.add(new TopicPartition("first",1));
        consumer.assign(topicPartitions);

        //消费数据
        while (true){
            //拉取数据 一秒拉取一次数据
            ConsumerRecords<String, String> poll = consumer.poll(Duration.ofSeconds(1));

            for (ConsumerRecord<String, String> stringStringConsumerRecord : poll) {

                System.out.println(stringStringConsumerRecord);
            }

        }

    }

}
